import React, { useState, useEffect } from 'react'
import {
  Card,
  Button,
  Input,
  Upload,
  DatePicker,
  ConfigProvider,
  Radio,
} from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { getUserInfo } from '~/utils/crypto'
import { UPLOAD_API } from '~/const/index'
import toast from '~/utils/toast'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import locale from 'antd/locale/zh_CN'
import { SEX_MAP, DEFAULT_AVATAR } from '~/const/index'
import { postUpdateUserInfoXhr } from '~/api/index'
import { encryptData } from '~/utils/crypto'
dayjs.locale('zh-cn')

const UserProfile: React.FC = () => {
  const [userInfo, setUserInfo] = useState<any>({
    avatar: null,
    birthday: null,
    email: null,
    gender: null,
    nickname: null,
    phone: '',
    username: '',
  })
  const [isEditing, setIsEditing] = useState(false)

  useEffect(() => {
    const userInfo = getUserInfo() || {}
    if (userInfo && Object.keys(userInfo)?.length > 0) {
      setUserInfo(userInfo)
    }
  }, [isEditing])

  const handleEditClick = () => {
    setIsEditing(!isEditing)
  }

  // 处理头像上传，修改头像
  const handleAvatarChange = (info: any) => {
    if (info.file.status === 'done') {
      // 假设上传成功后返回的URL
      const newAvatarUrl = info?.file?.response?.file?.path || ''
      setUserInfo({ ...userInfo, avatar: newAvatarUrl })
    } else if (info.file.status === 'error') {
      // 上传失败时弹出错误信息
      toast.error(
        `上传失败， ${info.file.error.message || '请重试或联系作者查看问题'}`
      )
    }
  }

  // 修改生日
  const handleDateChange = (date: any, dateString: any) => {
    console.log('dateString', dateString)
    setUserInfo({ ...userInfo, birthday: dateString })
  }

  // 修改性别
  const handleGenderChange = (e: any) => {
    setUserInfo({ ...userInfo, gender: e.target.value })
  }
  // 保存上传修改后的信息，并更新本地缓存的userInfo
  const handleSaveClick = async () => {
    try {
      // 调用 API 更新用户信息
      const response = await postUpdateUserInfoXhr({
        ...userInfo,
        userId: userInfo?.id,
      })
      if (response?.code === 200) {
        toast.success('用户信息更新成功')

        // 加密用户信息并存储到缓存中
        const encryptedUserInfo = encryptData(userInfo)
        localStorage.setItem('u_info_enc', encryptedUserInfo)
        window.location.reload()
      } else {
        toast.error(`更新失败: ${response?.message}`)
      }
    } catch (error) {
      toast.error('更新失败: 网络错误或服务器未响应')
    }
  }

  return (
    <ConfigProvider locale={locale}>
      <div
        className="profile-container"
        style={{ padding: '40px', fontSize: '16px' }}
      >
        <Card
          title="个人资料"
          style={{ width: 600, margin: '0 auto', padding: '30px' }}
        >
          <div style={{ marginBottom: '20px' }}>
            <strong
              style={{
                marginRight: '20px',
              }}
            >
              用户名:
            </strong>
            <span>{userInfo.username || ''}</span>
          </div>
          <div
            style={{
              marginBottom: '20px',
              display: 'flex',
              alignItems: 'center',
            }}
          >
            <strong
              style={{
                marginRight: '20px',
              }}
            >
              头像:
            </strong>

            <>
              <img
                src={userInfo?.avatar || DEFAULT_AVATAR}
                alt="头像"
                style={{
                  width: '100px',
                  height: '100px',
                  borderRadius: '50%',
                }}
              />
              {isEditing ? (
                <div style={{ marginLeft: '10px' }}>
                  <Upload
                    name="file"
                    action={UPLOAD_API}
                    onChange={handleAvatarChange}
                    showUploadList={false}
                  >
                    <Button icon={<UploadOutlined />}>修改头像</Button>
                  </Upload>
                </div>
              ) : null}
            </>
          </div>
          <div style={{ marginBottom: '20px' }}>
            <strong
              style={{
                marginRight: '20px',
              }}
            >
              生日:
            </strong>
            {isEditing ? (
              <DatePicker
                style={{ width: '200px' }}
                placeholder="请选择您的生日"
                value={userInfo.birthday ? dayjs(userInfo.birthday) : null}
                onChange={handleDateChange}
              />
            ) : (
              <span>{userInfo.birthday || '未设置'}</span>
            )}
          </div>
          <div style={{ marginBottom: '20px' }}>
            <strong
              style={{
                marginRight: '20px',
              }}
            >
              邮箱:
            </strong>
            {isEditing ? (
              <Input
                value={userInfo.email || ''}
                onChange={(e) =>
                  setUserInfo({ ...userInfo, email: e.target.value })
                }
              />
            ) : (
              <span>{userInfo.email || '未设置'}</span>
            )}
          </div>
          <div style={{ marginBottom: '20px' }}>
            <strong
              style={{
                marginRight: '20px',
              }}
            >
              性别:
            </strong>
            {isEditing ? (
              <Radio.Group
                value={userInfo.gender}
                onChange={handleGenderChange}
              >
                <Radio value={1}>男</Radio>
                <Radio value={2}>女</Radio>
                <Radio value={3}>保密</Radio>
              </Radio.Group>
            ) : (
              <span>{SEX_MAP?.[userInfo?.gender] || '未设置'}</span>
            )}
          </div>
          <div style={{ marginBottom: '20px' }}>
            <strong
              style={{
                marginRight: '20px',
              }}
            >
              昵称:
            </strong>
            {isEditing ? (
              <Input
                value={userInfo.nickname || ''}
                onChange={(e) =>
                  setUserInfo({ ...userInfo, nickname: e.target.value })
                }
              />
            ) : (
              <span>{userInfo.nickname || '未设置'}</span>
            )}
          </div>
          <div style={{ marginBottom: '20px' }}>
            <strong
              style={{
                marginRight: '20px',
              }}
            >
              电话:
            </strong>
            {isEditing ? (
              <Input
                value={userInfo.phone || ''}
                onChange={(e) =>
                  setUserInfo({ ...userInfo, phone: e.target.value })
                }
              />
            ) : (
              <span>{userInfo.phone || '未设置'}</span>
            )}
          </div>

          <div
            style={{
              width: '100%',
              marginTop: '30px',
            }}
          >
            {isEditing ? (
              <Button
                type="default"
                style={{
                  flex: 1,
                  marginRight: '10px',
                }}
                onClick={() => {
                  setIsEditing(false)
                }}
              >
                取消
              </Button>
            ) : null}
            <Button
              type="primary"
              style={{
                flex: 1,

                backgroundColor: '#4CAF50',
                borderColor: '#4CAF50',
              }}
              onClick={isEditing ? handleSaveClick : handleEditClick}
            >
              {isEditing ? '保存' : '修改'}
            </Button>
          </div>
        </Card>
      </div>
    </ConfigProvider>
  )
}

export default UserProfile
